package top.jiangqiang.qianyi.common.auth.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.jetbrains.annotations.Nullable;
import org.jspecify.annotations.NullMarked;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.pattern.PathPatternParser;
import top.jiangqiang.qianyi.common.auth.SessionHolder;
import top.jiangqiang.qianyi.common.auth.TokenPlayLoad;
import top.jiangqiang.qianyi.common.auth.model.UserDetails;
import top.jiangqiang.qianyi.common.auth.service.AuthService;
import top.jiangqiang.qianyi.common.auth.service.UserDetailService;
import top.jiangqiang.qianyi.common.constants.GlobalConstants;
import top.jiangqiang.qianyi.common.constants.auth.Platform;
import top.jiangqiang.qianyi.common.constants.http.Error401Status;
import top.jiangqiang.qianyi.common.exception.Error401Exception;
import top.jiangqiang.qianyi.common.properties.AuthProperties;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
@Slf4j
@NullMarked
public abstract class TokenAuthInterceptor implements HandlerInterceptor {
    protected final AuthProperties authProperties;
    protected final AuthService authService;
    protected final UserDetailService userDetailService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TokenPlayLoad tokenPlayLoad = null;
        if (authProperties.getMock()) {
            String userId = request.getHeader(GlobalConstants.SecurityConstants.USER_ID);
            String platform = request.getHeader(GlobalConstants.SecurityConstants.PLATFORM);
            if (StrUtil.isNotBlank(userId) && StrUtil.isNotBlank(platform)) {
                tokenPlayLoad = new TokenPlayLoad(Long.valueOf(userId), Platform.valueOf(platform));
            }
        } else {
            String token = request.getHeader(authProperties.getTokenKey());
            tokenPlayLoad = authService.validate(token);
        }

        if (tokenPlayLoad == null) {
            log.error("请求路径：{} 未提供有效Token", request.getRequestURI());
            throw new Error401Exception(Error401Status.UNAUTHORIZED_INVALID_TOKEN);
        }
        Platform platform = tokenPlayLoad.getPlatform();
        if (getSupportPlatform() != platform) {
            log.info("当前token和允许登录的平台不一致");
            throw new Error401Exception(Error401Status.UNAUTHORIZED_INVALID_TOKEN);
        }
        UserDetails user = userDetailService.getUserDetails(tokenPlayLoad.getUserId(), platform);
        if (user == null) {
            log.info("数据库中不存在该用户");
            throw new Error401Exception(Error401Status.UNAUTHORIZED_INVALID_TOKEN);
        }
        SessionHolder.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
        SessionHolder.remove();
    }

    protected abstract Platform getSupportPlatform();
}